package HTTP

import (
	"emb/emb_server/SQL/util"
	"emb/emb_server/logs"
	"encoding/json"
	"net/http"
	"strings"
)

// s objectID  string,nickname string,icon string,customInfo string
// r Message string,
func alterObjectData(w http.ResponseWriter, r *http.Request) {

	code := Success
	info := "success"
	var information interface{}

	defer func() {
		writeResult(w, code, info, information)
	}()

	config(w, r)

	err := r.ParseForm()
	if err != nil {
		code = errParseForm
		logs.Print("From:alterObjectData.ParseForm:---", err.Error())
		info = "From:alterObjectData.ParseForm:---" + err.Error()
		return
	}

	id := r.Form["objectID"]
	nickName := r.Form["nickname"]
	icon := r.Form["icon"]
	customList := r.Form["customInfo"]

	if id == nil {
		code = errEmtpyID
		logs.Print("From:alterObjectData.ParseForm:---objectID is null")
		info = "From:alterObjectData:---objectID is null"
		return
	}

	info, code, ok := queryObject(id[0])
	if !ok {
		return
	}

	if nickName == nil {
		code = errInvalidNickname
		logs.Print("From:alterObjectData:---nickName is null")
		info = "From:alterObjectData:---nickName is null"
		return
	}
	if icon == nil {
		code = errInvalidIcon
		logs.Print("From:alterObjectData:---icon is null")
		info = "From:alterObjectData:---icon is null"
		return
	}

	if customList == nil {
		code = errInvalidCustomInfo
		logs.Print("From:alterObjectData:---customInfo is null")
		info = "From:alterObjectData:---customInfo is null"
		return
	}

	if ok, code, info = checkOutId(id[0]); !ok {
		return
	}

	if ok, code, info = checkOutNickName(nickName[0]); !ok {
		return
	}

	if icon[0] == "" || icon[0] == "\"\"" {
		icon[0] = "default icon"
	}

	if ok, code, info = checkOutJsonInfo(customList[0]); !ok {
		return
	}

	customJson, ok := convertMap(customList[0])
	if !ok {
		info = mInvalidCustomInfo
		code = errInvalidCustomInfo
		return
	}

	custom, err := json.Marshal(customJson)
	if err != nil {
		code = errMarshalJSONFailed
		logs.Print("From:alterObjectData.Marshal:---", err.Error())
		info = "From:alterObjectData.Marshal:---json.Marshal error"
	}

	info, ok = updateObject(id[0], nickName[0], icon[0], custom)
	if !ok {
		code = errDBExecFailed
		return
	}

}

func updateObject(id string, nickName string, icon string, custom []byte) (string, bool) {
	info := "success"
	sql := "update objects set nickname = $1, icon = $2,custom = $3 where id = $4"
	// sql := "update objects set nickname = $1, icon = $2 where id = $3"
	if id == "" {
		logs.Print("From:alterObjectData:--- id输入有误,可能路径有误")
		info = "objectid  is null"
		return info, false
	}

	if icon == "" || icon == "\"\"" {
		icon = "default icon"
	}

	if nickName == "" {
		nickName = " "
	}

	db := util.GetDb()
	stmt, err := db.Prepare(sql)
	defer stmt.Close()
	if err != nil {
		logs.Print("From:alterObjectData.Prepare:---", err.Error())
		info = "From:alterObjectData.Prepare:---" + err.Error()
		return info, false
	}

	_, err = stmt.Exec(nickName, icon, custom, id)
	if err != nil {
		logs.Print("From:alterObjectData.Exec:---", err.Error())
		info = "From:alterObjectData.Exec:---" + err.Error()
		return info, false
	}
	return info, true
}

func queryObject(id string) (string, int, bool) {
	info := "success"
	sql := "select * from objects where id = $1"
	if id == "" {
		logs.Print("From:alterObjectData.queryObject:--- id = \"\"")
		info = "objectid  is null"
		return info, errInvalidID, false
	}

	db := util.GetDb()
	stmt, err := db.Prepare(sql)
	defer stmt.Close()
	if err != nil {
		logs.Print("From:alterObjectData.queryObject.Prepare:---", err.Error())
		info = "From:alterObjectData.queryObject.Prepare:---" + err.Error()
		return info, errDBQueryFailed, false
	}

	rows, err := stmt.Query(id)
	defer rows.Close()
	if err != nil {
		logs.Print("From:alterObjectData.queryObject.Query:---", err.Error())
		info = "From:alterObjectData.queryObject.Query:---" + err.Error()
		return info, errDBQueryFailed, false
	}

	if !rows.Next() {
		info = "the objectID is no exist"
		return info, errInvalidID, false
	}

	return info, Success, true
}

func convertMap(jsonInfo string) (map[string]interface{}, bool) {

	result := make(map[string]interface{})

	//jsonInfo = "{sex:male;age:17;friend:[asd,asd,asd]}"
	//strArray = [sex:male	age:17	friend:[asd,asd,asd]]
	strArray := strings.Split(strings.Trim(jsonInfo, "{} "), "*")

	for i := 0; i < len(strArray); i++ {
		valueAarry := strings.Split(strArray[i], ":")
		len := len(valueAarry)
		if len > 2 {
			return nil, false
		} else if len == 0 {
			return result, true
		} else if len == 1 {
			result[valueAarry[0]] = ""
			continue
		}
		result[valueAarry[0]] = valueAarry[1]
	}

	return result, true
}
